package com.hades.example.android.view_binding_example.dummy;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.RecyclerView;

import com.hades.example.android.view_binding_example.R;
import com.hades.example.android.view_binding_example.databinding.RecyclerviewDummyItemBinding;

import java.util.List;

public class DummyRecyclerViewAdapter extends RecyclerView.Adapter<DummyRecyclerViewAdapter.ViewHolder> {
    private static final String TAG = DummyRecyclerViewAdapter.class.getSimpleName();
    private int mViewHolderCount = 0;

    private final List<DummyItem> mValues;
    private IItemClickAction mListener;

    public DummyRecyclerViewAdapter(List<DummyItem> items, IItemClickAction listener) {
        mValues = items;
        mListener = listener;
    }

    public void setListener(IItemClickAction listener) {
        mListener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_dummy_item, parent, false);
        mViewHolderCount++;
        Log.d(TAG, "ViewHolder: " + mViewHolderCount);
        return new ViewHolder(RecyclerviewDummyItemBinding.bind(view));
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        Log.d(TAG, "onBindViewHolder: position=" + position);

        holder.item = mValues.get(position);
        holder.binding.id.setText(String.valueOf(mValues.get(position).id));
        holder.binding.title.setText(String.valueOf(mValues.get(position).colo2));
        holder.binding.getRoot().setOnClickListener(v -> {
            if (null != mListener) {
                mListener.onItemClickListener(holder.item);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mValues.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public DummyItem item;
        private final RecyclerviewDummyItemBinding binding;

        public ViewHolder(RecyclerviewDummyItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        @Override
        public String toString() {
            return super.toString() + " '" + binding.title.getText() + "'";
        }
    }
}
